import { login, getUserInfoApi, getUserDetailInfoApi } from '@/api/user'
import { getToken, setToken, removeToken, setTokenTime } from '@/utils/auth'
import { resetRouter } from '@/router/index'
const state = {
  token: getToken(),
  UserInfo: {}
}

const mutations = {
  setToken(state, payload) {
    state.token = payload
  },
  setUserInfo(state, payload) {
    // 后端返回的数据不对，手动修改权限点 自己模拟假数据
    payload.roles.points = ['PERMISSION_ADD', 'PERMISSION_DEL', 'USER_DEL', 'USER_ROLE']
    state.UserInfo = payload
  },
  removeToken(state, payload) {
    state.token = null
    removeToken()
  }
}

const actions = {
  // token值
  async  login(context, payload) {
    const res = await login(payload)
    console.log('token值', res)
    context.commit('setToken', res)
    setToken(res)
    // 存入时间戳
    setTokenTime()
  },
  // 用户资料
  async getUserInfo(context) {
    const res = await getUserInfoApi()
    const userDetail = await getUserDetailInfoApi(res.userId)
    context.commit('setUserInfo', { ...res, ...userDetail })
    console.log(res.roles, '用户权限')
    return res
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    // 退出清空路由规则
    resetRouter()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

